<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input
        v-model="listQuery.product_id"
        placeholder="商品ID"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      /> -->
      <!-- <el-select
        v-model="listQuery.status"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleFilter"
      > -->
        <el-option
          v-for="item in statusOptions"
          :key="item.key"
          :label="item.display_name"
          :value="item.key"
        />
      </el-select>
      <!-- <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button> -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增拼团
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="商品ID" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.product_id }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="商品名称" prop="product.name" min-width="200px">
      
      </el-table-column>
      <el-table-column label="商品图片"  min-width="200px">
        <template slot-scope="{row}">
          <img style="width:100px;height:100px;" :src="row.product.main_image" alt="">
        </template>
    </el-table-column>
      
      <el-table-column label="拼团人数" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.people_number }}人</span>
        </template>
      </el-table-column>
      
      <el-table-column label="持续时间" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.duration }}小时</span>
        </template>
      </el-table-column>
      
      <el-table-column label="状态" class-name="status-col" width="100px">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status !== 0"
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleModifyStatus(row, 0)"
          >
            停用
          </el-button>
          <el-button
            v-if="row.status === 0"
            size="mini"
            type="success"
            icon="el-icon-check"
            @click="handleModifyStatus(row, 1)"
          >
            启用
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row,$index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="选择商品" prop="product_id">
          <div class="product-selector">
            <el-input
              v-model="selectedProductName"
              placeholder="请选择商品"
              readonly
              style="width: 100%"
              @click="showProductSelector = true"
            >
              <el-button slot="append" icon="el-icon-search" @click="showProductSelector = true">
                选择商品
              </el-button>
            </el-input>
            <div v-if="selectedProduct" class="selected-product-info">
              <el-tag type="info" size="small">
                ID: {{ selectedProduct.id }} | {{ selectedProduct.name }}
              </el-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="拼团人数" prop="people_number">
          <el-input-number v-model="temp.people_number" :min="2" :max="10" />
        </el-form-item>
        <el-form-item label="持续时间" prop="duration">
          <el-input-number v-model="temp.duration" :min="1" :max="168" />
          <span style="margin-left: 10px;">小时</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 商品选择弹窗 -->
    <ProductSelector
      :visible.sync="showProductSelector"
      product-type="group"
      @confirm="handleProductSelect"
    />
  </div>
</template>

<script>
import { fetchGroupList, createGroup, updateGroup, deleteGroup } from '@/api/shopping'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ProductSelector from '@/components/ProductSelector'

const statusOptions = [
  { key: 0, display_name: '停用' },
  { key: 1, display_name: '启用' }
]

// arr to obj ,such as { CN : "中国", US : "美国" }
const statusKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PingdanList',
  components: { Pagination, ProductSelector },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      return statusKeyValue[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        product_id: undefined,
        status: undefined
      },
      showProductSelector: false,
      selectedProduct: null,
      selectedProductName: '',
      statusOptions,
      temp: {
        id: undefined,
        product_id: '',
        people_number: 2,
        duration: 24
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑拼团',
        create: '新增拼团'
      },
      rules: {
        product_id: [{ required: true, message: '请选择商品', trigger: 'change' }],
        people_number: [{ required: true, message: '拼团人数不能为空', trigger: 'blur' }],
        duration: [{ required: true, message: '持续时间不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchGroupList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.data.length
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      const action = status === 1 ? '启用' : '停用'
      this.$confirm(`确定要${action}该拼团吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: row.id.toString(),
          product_id: row.product_id.toString(),
          people_number: row.people_number.toString(),
          duration: row.duration.toString(),
          status: status.toString()
        }
        updateGroup(data).then(() => {
          row.status = status
          this.$message({
            message: `${action}成功`,
            type: 'success'
          })
        }).catch(() => {
          this.$message({
            message: `${action}失败，请重试`,
            type: 'error'
          })
        })
      }).catch(() => {
        this.$message({
          message: '已取消操作',
          type: 'info'
        })
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        product_id: '',
        people_number: 2,
        duration: 24
      }
      this.selectedProduct = null
      this.selectedProductName = ''
    },
    // 处理商品选择
    handleProductSelect(product) {
      this.selectedProduct = product
      this.selectedProductName = product.name
      this.temp.product_id = product.id
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            product_id: this.temp.product_id.toString(),
            people_number: this.temp.people_number.toString(),
            duration: this.temp.duration.toString()
          }
          createGroup(data).then(() => {
            this.getList() // 重新获取列表
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      
      // 设置已选择的商品信息
      if (row.product_id) {
        this.selectedProduct = {
          id: row.product_id,
          name: row.title || `商品ID: ${row.product_id}`
        }
        this.selectedProductName = this.selectedProduct.name
      }
      
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.temp.id.toString(),
            product_id: this.temp.product_id.toString(),
            people_number: this.temp.people_number.toString(),
            duration: this.temp.duration.toString()
          }
          updateGroup(data).then(() => {
            this.getList() // 重新获取列表
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该拼团, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGroup(row.id).then(() => {
          this.list.splice(index, 1)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}

.filter-container .filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.link-type {
  color: #337ab7;
  cursor: pointer;
}

.link-type:hover {
  color: #23527c;
}

.product-selector {
  width: 100%;
}

.selected-product-info {
  margin-top: 8px;
}
</style>
